package net.wicp.tams.common.apiext.tools;

import java.io.File;

import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.ArrayUtils;

import net.wicp.tams.common.apiext.IOUtil;

public class PathEndFilter  implements IOFileFilter{
	
	//private final String root;//要过滤的根目录
	private final String[] excludePaths;//要选择的路径
	private final String[] includePaths;//需要包括的路径
	
	
	public PathEndFilter(String... excludePaths) {
		this.excludePaths=conver(null,excludePaths);
		this.includePaths=null;
	}
	public PathEndFilter(String root,String[] excludePaths) {
		this.excludePaths=conver(root,excludePaths);
		this.includePaths=null;
	}
	public PathEndFilter(String root,String[] excludePaths,String[] includePaths) {
		this.excludePaths=conver(root,excludePaths);
		this.includePaths=conver(root,includePaths);
	}
	
	private String[] conver(String root,String... oriArys) {
		if(ArrayUtils.isEmpty(oriArys)) {
			return new String[] {};
		}
		String[] ret=new String[oriArys.length];
		for (int i = 0; i < ret.length; i++) {
			ret[i] =  IOUtil.mergeFolderAndFilePath(root, oriArys[i]);// oriArys[i].replace("\\", "/");
		}
		return ret;
	}
	
	/****
	 * FileUtils.listFiles起作用
	 */
	@Override
	public boolean accept(File file) {
		if(ArrayUtils.isEmpty(excludePaths)&&ArrayUtils.isEmpty(includePaths)) {
			return true;
		}
		for (String excludePath : excludePaths) {		
			boolean eq = isFilter(file.getPath(),excludePath);// file.getPath().replace("\\", "/").equals(excludePath);
			if(eq) {
				return false;
			}
		}
		if(ArrayUtils.isNotEmpty(includePaths)) {
			for (String includePath : includePaths) {		
				boolean eq =isFilter(file.getPath(),includePath);
				if(eq) {
					return true;
				}
			}
			return false;
		}
		
		return true;
	}
	
	
	private boolean isFilter(String thePath,String isPath) {
		String replace = thePath.replace("\\", "/");
		if(isPath.endsWith("/*")||isPath.endsWith("\\*")) {
			String substring = isPath.substring(0,isPath.length()-2);
			return replace.startsWith(substring);
		}else {
			return replace.equals(isPath);
		}
	}

	/**
	 * new File("").list(filter)(只对第一层起作用) 的api起作用
	 */
	@Override
	public boolean accept(File dir, String name) {
		if(ArrayUtils.isEmpty(excludePaths)&&ArrayUtils.isEmpty(includePaths)) {
			return true;
		}		
		for (String excludePath : excludePaths) {	
			boolean eq = isFilter(IOUtil.mergeFolderAndFilePath(dir.getPath(), name),excludePath);
			if(eq) {
				return false;
			}
		}		
		if(ArrayUtils.isNotEmpty(includePaths)) {
			for (String includePath : includePaths) {	
				boolean endsWith = isFilter(IOUtil.mergeFolderAndFilePath(dir.getPath(), name),includePath);
				if(endsWith) {
					return true;
				}
			}
			return false;
		}		
		return true;
	}

}
